package com.crs.interceptor;

import com.crs.context.BaseContext;
import com.crs.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.invoke.MethodHandle;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截请求: {} {}", request.getMethod(), request.getRequestURI());
        log.info("Handler类型: {}", handler.getClass().getName());
        // 1. 放行非控制器请求（如静态资源）
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        try{
            String token = request.getHeader("Authorization");
            Claims claims = JwtUtil.parseJWT(token);
            Long userId = ((Number)claims.get("userId")).longValue();
            BaseContext.setCurrentId(userId);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
